<!--
基本信息--使用elelmentuiplus
-->

<template>
  <div
  v-loading="loading"
  element-loading-text="数据保存中.."
  >
    <el-form

    :model="baseInfo" :rules="rules" ref="formRef" size="small">
      <!--   第一行   -->
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item label="合同类别" prop="Type">
            <!-- <el-select
                :disabled="isBg || !isShowSubBut"
                v-model="baseInfo.Type"
                filterable
                size="small"
                clearable
                remote
                reserve-keyword
                placeholder="请选择合同类型"
                remote-show-suffix
            >
              <el-option label="正式合同" value="0"></el-option>
              <el-option label="虚拟合同" value="1"></el-option>
            </el-select> -->
            <el-select
                @change="selectchanged"
                v-model="baseInfo.Type"
                disabled
                filterable
                size="small"
                clearable
                remote
                reserve-keyword
                placeholder="请选择合同类型"
                remote-show-suffix
            >
              <el-option label="正式合同" value="0"></el-option>
              <el-option label="虚拟合同" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="合同名称" prop="ContractName" >
            <el-input size="small" v-model="baseInfo.ContractName" placeholder="请输入合同名称" :disabled="!isShowSubBut"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="baseInfo.Type =='0'">
          <el-form-item label="合同编号" prop="ContractNum" >
            <el-input size="small" v-model="baseInfo.ContractNum" placeholder="请输入合同编号" :disabled="!isShowSubBut"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="合同类型" prop="ContractType">
            <el-select
                :disabled="!isShowSubBut"
                v-model="baseInfo.ContractType"
                filterable
                clearable
                remote
                size="small"
                reserve-keyword
                placeholder="请选择合同类型"
                remote-show-suffix
            >
              <el-option label="销售合同" value="0"></el-option>
              <el-option label="采购合同" value="1"></el-option>
              <el-option label="委托合同" value="2"></el-option>
              <el-option label="服务合同" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="工作号" prop="JobNum">
            <el-input size="small" v-model="baseInfo.JobNum" placeholder="请输入工作号" :disabled="!isShowSubBut"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="售前号" prop="SaleNum">
            <el-input size="small" v-model="baseInfo.SaleNum" placeholder="请输入售前号" :disabled="!isShowSubBut"></el-input>
          </el-form-item>
        </el-col>



      </el-row>
      <!--   第二行   -->
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item label="项目名称" prop="ProjectName">
            <el-input size="small" v-model="baseInfo.ProjectName" placeholder="请输入项目名称" :disabled="!isShowSubBut"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="支付款项" prop="Payment">
            <el-select
                :disabled="!isShowSubBut"
                v-model="baseInfo.Payment"
                filterable
                clearable
                collapse-tags
                multiple
                remote
                reserve-keyword
                placeholder="请选择支付款项"
                remote-show-suffix
            >
              <el-option label="电汇" value="0"></el-option>
              <el-option label="支票" value="1"></el-option>
              <el-option label="银行承兑" value="2"></el-option>
              <el-option label="保理（无追索权）" value="3"></el-option>
              <el-option label="供应链融资（无追索权）" value="4"></el-option>
              <el-option label="商业承兑（原则不允许）" value="5"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="税率" prop="Rate">
            <el-input v-model="baseInfo.Rate" placeholder="请输入税率" disabled>
              <template #append>%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="合同金额" prop="ContractAmount">
            <el-input v-model="baseInfo.ContractAmount" disabled  placeholder="请输入合同金额" @change="numSubChange(null,'ContractAmount',null)">
              <template #append>
                元
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="客户合同编号" prop="CustContractNum">
            <el-input size="small" v-model="baseInfo.CustContractNum" placeholder="请输入客户合同编号" :disabled="!isShowSubBut"> </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="客户" prop="CustCode">
            <el-select
                :disabled="!isShowSubBut"
                v-model="baseInfo.CustCode"
                filterable
                remote
                size="small"
                reserve-keyword
                placeholder="请选择客户"
                :remote-method="cnvbasdocMethod"
                :loading="state.loading"
                @change="changeCustCode"
                remote-show-suffix
            >
              <el-option
                  v-for="item in cusoptions"
                  :key="item.cCusCode"
                  :label="item.ccusabbname"
                  :value="item.cCusCode">
                <span style="float: left">{{ item.ccusabbname }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">【{{item.cCusCode}}】</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="4">
                  <el-form-item label="标的物是否合规" prop="IsCompliance">
                    <el-select
                        disabled
                      v-model="baseInfo.IsCompliance"
                      filterable
                      clearable
                      remote
                      size="small"
                      reserve-keyword
                      placeholder="请选择标的物是否合规"
                      remote-show-suffix
                    >
                      <el-option label="是" :value="true"></el-option>
                      <el-option label="否" :value="false"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>-->



        <!--        <el-col :span="4">-->
        <!--          <el-form-item label="客户地址" prop="CustAdd">-->
        <!--            <el-input  v-model="baseInfo.CustAdd" placeholder="请输入客户地址" disabled> </el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="4">
                  <el-form-item label="是否补录" prop="IsBL">
                    <el-select
                      :disabled="!isShowSubBut"
                      v-model="baseInfo.IsBL"
                      filterable
                      clearable
                      remote
                      reserve-keyword
                      placeholder="请选择是否补录"
                      remote-show-suffix
                    >
                      <el-option label="是" value="是"></el-option>
                      <el-option label="否" value="否"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>-->

      </el-row>
      <!--   第三行   -->
      <el-row :gutter="20">

        <!--        <el-col :span="4">
                  <el-form-item label="开户行" prop="BankCode">
                    <el-input v-model="baseInfo.BankCode" placeholder="请输入开户行" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="银行账号" prop="BankAccount">
                    <el-input v-model="baseInfo.BankAccount" placeholder="请输入银行账号" disabled> </el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item label="税号" prop="Tax">
                    <el-input v-model="baseInfo.Tax" placeholder="请输入税号" disabled > </el-input>
                  </el-form-item>
                </el-col>-->

      </el-row>

      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="交付时间" prop="DeliveryDate">
            <el-date-picker
                :disabled="!isShowSubBut"
                v-model="baseInfo.DeliveryDate"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                :disabled-date="disabledDate"
                clearable
                placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="交付地点" prop="DeliveryLocation">
            <el-input v-model="baseInfo.DeliveryLocation" placeholder="请输入交付地点" :disabled="!isShowSubBut"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="签订地点" prop="SigningLocation">
            <el-input v-model="baseInfo.SigningLocation" placeholder="请输入签订地点" :disabled="!isShowSubBut"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="卸货方式" prop="Unload">
            <el-select
                :disabled="!isShowSubBut"
                v-model="baseInfo.Unload"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择卸货方式"
                remote-show-suffix
            >
              <el-option label="甲方卸货" value="0"></el-option>
              <el-option label="乙方卸货" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="包装要求" prop="PackRequirement">
            <el-select
                :disabled="!isShowSubBut"
                v-model="baseInfo.PackRequirement"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择包装要求"
                remote-show-suffix
            >
              <el-option label="普通包装" value="0"></el-option>
              <el-option label="木箱包装" value="1"></el-option>
              <el-option label="出口包装" value="2"></el-option>
              <el-option label="特殊包装" value="3"></el-option>
              <el-option label="其他" value="4"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="包装说明" prop="PackRequirementInfo">
            <el-input v-model="baseInfo.PackRequirementInfo" placeholder="请输入包装说明" :disabled="!isShowSubBut"> </el-input>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">

        <el-col :span="4">
          <el-form-item label="是否合同模板" prop="IsMoudel">
            <el-select
                disabled
                v-model="baseInfo.IsMoudel"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择是否合同模板合同"
                remote-show-suffix
            >
              <el-option label="是" :value="true"></el-option>
              <el-option label="否" :value="false"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="单据日期" prop="DDate2">
            <el-date-picker
                :disabled="!isShowSubBut"
                v-model="baseInfo.DDate2"
                style="width: 100%"
                format="YYYY-MM-DD"

                type="date"
                clearable
                placeholder="选择单据日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="签订日期" prop="Ddate">
            <el-date-picker
                :disabled="!isShowSubBut"
                v-model="baseInfo.Ddate"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                :disabled-date="disabledDate"
                clearable
                placeholder="选择签订日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否安装" prop="IsInstall">
            <el-select
                :disabled="!isShowSubBut"
                v-model="baseInfo.IsInstall"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择是否安装"
                remote-show-suffix
            >
              <el-option label="是" value="是"></el-option>
              <el-option label="否" value="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="业务员" prop="SaleCode">
            <el-select
                :disabled="!isShowSubBut"
                @change="changeSalesman"
                v-model="baseInfo.SaleCode"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择业务员"
                remote-show-suffix
            >
              <el-option
                  :label="item.cPsn_Name"
                  :value="item.cPsn_Num"
                  v-for="(item, index) in state.userList"
                  :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否预开票" prop="IsYKP">
            <el-select
                :disabled="(!isShowSubBut || baseInfo.IsMoudel)"
                v-model="baseInfo.IsYKP"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择是否预开票"
                remote-show-suffix
            >
              <el-option label="是" value="是"></el-option>
              <el-option label="否" value="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="24">
          <el-form-item label="阶段性文件" prop="PhasedFile">
            <el-checkbox-group v-model="baseInfo.PhasedFile" :disabled="!isShowSubBut">
              <el-checkbox value="交货验收" name="type" disabled>

                交货验收
              </el-checkbox>
              <el-checkbox value="通电验收" name="type">
                通电验收
              </el-checkbox>
              <el-checkbox value="结算资料" name="type">
                结算资料
              </el-checkbox>
              <el-checkbox value="预收资料" name="type">
                预收资料
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="baseInfo.PhasedFile?.includes('通电验收')">
          <el-form-item label="通电验收文件" prop="TDYSJDFile" >
            <el-select
                :disabled="!isShowSubBut"
                multiple
                v-model="baseInfo.TDYSJDFile"
                filterable
                clearable
                collapse-tags
                remote
                reserve-keyword
                placeholder="请选择通电验收文件"
                remote-show-suffix
            >
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in needFiles" :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="baseInfo.PhasedFile?.includes('交货验收')">
          <el-form-item label="交货验收文件" prop="JHYSJDFile" >
            <el-select
                multiple
                v-model="baseInfo.JHYSJDFile"
                filterable
                collapse-tags
                clearable
                :disabled="!isShowSubBut"
                remote
                reserve-keyword
                placeholder="请选择交货验收文件"
                remote-show-suffix
            >
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in needFiles" :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6" v-if="baseInfo.PhasedFile?.includes('结算资料')">
          <el-form-item label="结算资料文件" prop="JSJDFile" >
            <el-select
                multiple
                collapse-tags
                v-model="baseInfo.JSJDFile"
                filterable
                clearable
                :disabled="!isShowSubBut"
                remote
                reserve-keyword
                placeholder="请选择结算资料文件"
                remote-show-suffix
            >
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in needFiles" :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="baseInfo.PhasedFile?.includes('预收资料')">
          <el-form-item label="预收资料文件" prop="YSZLFile" >
            <el-select
                multiple
                collapse-tags
                v-model="baseInfo.YSZLFile"
                filterable
                clearable
                :disabled="!isShowSubBut"
                remote
                reserve-keyword
                placeholder="请选择预收资料文件"
                remote-show-suffix
            >
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in needFiles" :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>



        <el-col :span="24">
          <el-form-item label="补充说明" prop="UnloadConvention">
            <el-input v-model="baseInfo.UnloadConvention" :disabled="!isShowSubBut"   type="textarea" :rows="2" placeholder="请输入补充说明"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <div>
            <div style="width: 100%">
              <vxe-table
                  ref="xTable"
                  id="singleTab"
                  class="mytable-scrollbar"
                  border
                  show-overflow
                  show-header-overflow
                  show-footer-overflow
                  height="600"
                  maxHeight="300"
                  :size="'mini'"
                  keep-source
                  :scrollbarConfig="{x: {position: 'top'}}"
                  :row-config="{keyField: 'Id'}"
                  :data="state.table.data"
                  :column-config="{resizable: true}"
                  :virtual-y-config="{enabled: true, gt: 0}"
              >
                <vxe-column field="LineNum" title="行号" width="60" fixed="left"></vxe-column>

                <vxe-column field="CinvCode" title="存货编码" width="130">
                  <template #default="{ row }">
                    <el-select
                        v-model="row.CinvCode"
                        filterable
                        remote
                        disabled
                        reserve-keyword
                        placeholder="请选择存货"
                        :remote-method="query => remoteMethod(query, row)"
                        :loading="state.loading"
                        @change="(e) => updateInv(e, row)"
                        size="small"
                        style="width: 100%"
                    >
                      <el-option
                          v-for="item in state.options"
                          :key="item.cInvCode"
                          :label="item.cInvCode"
                          :value="item.cInvCode"
                      >
                        <span style="float: left">{{ item.cInvName }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ item.cInvCode }}
                  </span>
                      </el-option>
                    </el-select>
                  </template>
                </vxe-column>

                <vxe-column field="CinvName" title="存货名称" width="200"></vxe-column>
                <vxe-column field="Unit" title="单位" width="60"></vxe-column>

                <vxe-column field="CustCinvCode" title="合同序号" width="80">
                  <template #default="{ row }">
                    <el-input
                        disabled
                        v-model="row.CustCinvCode"
                        placeholder="请输入合同序号"
                        size="small"
                        style="width: 100%"
                        filterable clearable />
                  </template>
                </vxe-column>

                <vxe-column field="CustCinvName" title="客户存货名称" width="220">
                  <template #default="{ row }">
                    <el-input
                        disabled
                        v-model="row.CustCinvName"
                        placeholder="请输入客户存货名称"
                        size="small"
                        style="width: 100%"
                        filterable clearable />
                  </template>
                </vxe-column>

                <vxe-column field="CustCinvAdd" title="客户存货规格" width="220"></vxe-column>

                <vxe-column field="JFDate" title="交付时间" width="140">
                  <template #default="{ row }">
                    <el-date-picker
                        disabled
                        v-model="row.JFDate"
                        type="date"
                        placeholder="请选择交付时间"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        clearable
                        size="small"
                        style="width: 100%"
                    />
                  </template>
                </vxe-column>

                <vxe-column field="Price" title="含税单价" width="120">
                  <template #default="{ row, rowIndex }">
                    <el-input
                        disabled
                        v-model="row.Price"
                        placeholder="请输入含税单价"
                        clearable
                        @change="(e)=>numChange(e, row, rowIndex)"
                        size="small"
                        style="width: 100%"
                    />
                  </template>
                </vxe-column>

                <vxe-column field="Quantity" title="数量" width="120">
                  <template #default="{ row, rowIndex }">
                    <el-input
                        disabled
                        v-model="row.Quantity"
                        placeholder="请输入数量"
                        clearable
                        @change="(e)=>numChange(e, row, rowIndex)"
                        size="small"
                        style="width: 100%"
                    />
                  </template>
                </vxe-column>

                <vxe-column field="Amount" title="价税合计" width="110"></vxe-column>

                <vxe-column field="Rate" title="税率" width="120">
                  <template #default="{ row, rowIndex }">
                    <el-input
                        disabled
                        v-model="row.Rate"
                        placeholder="请输入税率"
                        clearable
                        @change="(e)=>numChange(e, row, rowIndex)"
                        size="small"
                        style="width: 100%"
                    />
                  </template>
                </vxe-column>

                <vxe-column field="Tax" title="税额" width="110"></vxe-column>
                <vxe-column field="iNatPrice" title="无税单价" width="110"></vxe-column>
                <vxe-column field="iNatAmount" title="无税金额" width="110"></vxe-column>
                <vxe-column field="TDYSFile" title="通电验收文件" width="110"></vxe-column>
                <vxe-column field="FHTZDFile" title="交货验收文件" width="110"></vxe-column>
                <vxe-column field="JSDFile" title="结算资料" width="110"></vxe-column>
                <vxe-column field="YSaleQty" title="已下订单数量" width="120"></vxe-column>
                <vxe-column field="YSaleAmount" title="已下订单金额" width="120"></vxe-column>
                <vxe-column field="YFHQty" title="已发货数量" width="100"></vxe-column>
                <vxe-column field="YFHAmount" title="已发货金额" width="100"></vxe-column>
                <vxe-column field="YJSQty" title="已结算数量" width="100"></vxe-column>
                <vxe-column field="YJSAmount" title="已结算金额" width="100"></vxe-column>
                <vxe-column field="YFHYSQty" title="已发货验收数量" width="140"></vxe-column>
                <vxe-column field="YTDYSQty" title="已通电验收数量" width="140"></vxe-column>
                <vxe-column field="Remark" title="备注" width="140"></vxe-column>
                <vxe-column field="IsJS" title="据实结算" width="80" fixed="right">
                  <template #default="{ row }">
                    <el-switch v-model="row.IsJS" />
                  </template>
                </vxe-column>

                <vxe-column field="RowState" title="状态" width="80" fixed="right">
                  <template #default="{ row }">
                    <el-select
                        v-model="row.RowState"
                        filterable
                        remote
                        disabled
                        reserve-keyword
                        placeholder="请选择状态"
                        remote-show-suffix
                        style="width: 100%"
                    >
                      <el-option label="正常" value="1"></el-option>
                      <el-option label="关闭" value="0"></el-option>
                    </el-select>
                  </template>
                </vxe-column>
              </vxe-table>
          </div>
        </div>
      </el-col>
      <el-col :span="24">
        <div class="mt20">
          <t-table
              title="支付标准"
              :table="state.tableZfBz"
              show-summary
              :columns="state.tableZfBz.columns"
              :isShowPagination="false"
              ref="singleTowEdit"
              :listTypeInfo="state.listTypeInfo"
              @handleEvent="handleEvent"
              @validateError="validateError"
          >
            <template #toolbar>
              <el-button type="primary" @click="addTowTable" >新增一行</el-button>
            </template>
            <template #TermContent="{ scope }">
              <!--                <EditableNumbers :text="scope.row.TermContent" />-->
                <el-input type="textarea" v-model="scope.row.TermContent" :autosize="{ minRows: 2, maxRows: 4 }"  />
              </template>

              <template #operator="{ scope }">
                <el-button type="primary" link  @click="editDel(scope.$index,scope)">删除</el-button>
              </template>

              <template #TermID="{ scope }">
                <el-select
                    v-model="scope.row[scope.column.property]"
                    filterable
                    remote
                    :disabled="!isBg"
                    reserve-keyword
                    placeholder="请选择支付条件"
                    remote-show-suffix
                    @change="(e) => updateZfTk(e, scope.row)"
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in state.listTypeInfo"
                      :key="item.Id"
                      :label="item.Content"
                      :value="item.Id"
                  >
                  </el-option>
                </el-select>
              </template>
              <template #ZfType="{ scope }">
                <el-select

                    v-model="scope.row[scope.column.property]"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请选择支付类型"
                    remote-show-suffix
                    style="width: 100%"
                >
                  <el-option label="预付款" value="预付款"></el-option>
                  <el-option label="进度款" value="进度款"></el-option>
                  <el-option label="竣工结算款" value="竣工结算款"></el-option>
                  <el-option label="质保金" value="质保金"></el-option>
                  <el-option label="到货款" value="到货款"></el-option>
                  <el-option label="提货款" value="提货款"></el-option>
                  <el-option label="通电验收款" value="通电验收款"></el-option>
                  <el-option label="验收款" value="验收款"></el-option>
                  <el-option label="运行款" value="运行款"></el-option>
                </el-select>
              </template>

              <template #Ratio="{ scope }">
                <el-input-number  v-model="scope.row[scope.column.property]" :min="0" :step="0.1" @change="(e)=>numSubChange(e,'Ratio',scope)"></el-input-number>
              </template>
              <template #Amount="{ scope }">
                <el-input  v-model="scope.row[scope.column.property]"  @change="(e)=>numSubChange(e,'Amount',scope)"></el-input>
              </template>
              <template #uploadFile3="{ scope }">
                <upload :limit="1" v-model="scope.row[scope.column.property]"></upload>
              </template>
            </t-table>
          </div>
        </el-col>
      </el-row>

    </el-form>




  </div>
</template>

<script setup>
import {onMounted, ref, toRefs} from "vue";
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import {findbaseBasicManage, GetInventory2, GetTK,DetailImoprtExcel} from "@/api/base";
import {checkForm, debounce} from "@/utils/util";
import {checkFildsStore} from "@/stores/modules/checkFilds";
import {Upload} from "@element-plus/icons-vue";
import XLSX from "xlsx";
import {getDataToXlsxFile, importAdd} from "@/utils/excel";
import {ElMessage, TableV2FixedDir} from "element-plus";
import {emitter} from "@/hooks/evenBus"
import { VxeTable, VxeColumn } from 'vxe-table'
import 'vxe-table/lib/style.css'

const emit = defineEmits(['submit',"update:SubList"])
defineOptions({ name: 'EntryBaseInfo' })
const props = defineProps({
  baseInfo: {
    type: Object,
    default: {}
  },
  rules: {
    type: Object,
    default: () => {
      return {}
    }
  },
  subList: {
    type: Array,
    default: () => {
      return []
    }
  },
  tremZF: {
    type: Array,
    default: () => {
      return []
    }
  },
  Id:{
    type: String,
    default: ''
  },
  isBg:{
    type: Boolean,
    default: () => {
      return false
    }
  },
  isAdd:{
    type: Boolean,
    default: () => {
      return false
    }
  },
  isShowSubBut:{
    type: Boolean,
    default: () => {
      return false
    }
  },
  loading:{
    type: Boolean,
    default: () => {
      return false
    }
  }
})

let {
  baseInfo,
  rules,
  subList,
  tremZF,
  Id,
  isShowSubBut,
  isBg,
  isAdd,
  loading
} = toRefs(props)


//深度监听
// watch(
//     [baseInfo, rules, subList, tremZF, Id, isShowSubBut, isBg, isAdd,loading],
//     (newValue, oldValue) => {
//       console.log(loading);
//     },
//     {
//       deep: true,
//     }
// );
// watch(() => props.loading, (newValue, oldValue) => {
//   console.log(loading.value);
// // console.log(props);
//     loading.value = newValue

//     //Main.value=newValue?.Main;
//     //console.log(Main.value);
//   }, { deep: true },
// )
//subList数据渲染
const singleEdit = ref(null)
const singleTowEdit = ref(null)
let formRef =ref({})
const selectchanged=(vl)=>
{
  emitter.emit('select-changed',vl)
}
let needFiles =ref([
  {
    label: '其他',
    value:'其他'
  },
  {
    label: '生产厂厂内验收单',
    value:'生产厂厂内验收单'
  },
  {
    label: '开箱验收单',
    value:'开箱验收单'
  },
  {
    label: '交(到)货验收清单',
    value:'交(到)货验收清单'
  },
  {
    label: '安装指导确认单（含签到表及培训证明材料）',
    value:'安装指导确认单（含签到表及培训证明材料）'
  },
  {
    label: '安装调试验收单',
    value:'安装调试验收单'
  },
  {
    label: '通电验收单',
    value:'通电验收单'
  },
  {
    label: '编程调试验收报告',
    value:'编程调试验收报告'
  },
  {
    label: '施工成本挂账确认单',
    value:'施工成本挂账确认单'
  },
  {
    label: '施工工时单',
    value:'施工工时单'
  },
  {
    label: '隐蔽性工程确认签证单',
    value:'隐蔽性工程确认签证单'
  },
  {
    label: '工程量确认签证单',
    value:'工程量确认签证单'
  },
  {
    label: '价格审核确认单',
    value:'价格审核确认单'
  },
  {
    label: '项目预算书',
    value:'项目预算书'
  },
  {
    label: '进度结算报告',
    value:'进度结算报告'
  },
  {
    label: '工程决算报告',
    value:'工程决算报告'
  },
])


const checkFild = checkFildsStore()

// 编辑单元格监听事件
const handleEvent = (type, val, index) => {

}
// 清除校验规则
const validateTable = (resultArr) => {
  // singleEdit.value.saveMethod(data => {
  //
  // })
  singleTowEdit.value.saveMethod(data => {

  })
  checkForm(formRef.value,checkFild)
}
// 重置表单
const reset = () => {
  singleEdit.value.resetFields()
}
const editDelT = (index) => {

  state.table.data.splice(index, 1)
}
const editDel = (index, row) => {

  state.tableZfBz.data.splice(index, 1)
}
// 错误校验提示
const validateError = list => {
  list.map(val => {
    setTimeout(() => {
      console.log(val,"121212")
      // ElNotification.error({
      //   title: '提示',
      //   message: `${title.value}是必填项！`,
      //   offset: 200,
      // })
      checkFild.setData(val)
    }, 100)
  })
}

function changeSalesman(e) {
  //过滤客户
  let useroptions = state.userList.filter(its =>
      its.cPsn_Num.toLowerCase() === e.toLowerCase()
  )
  if (useroptions) {
    //赋值
    baseInfo.value.SaleName = useroptions[0].cPsn_Name
    console.log(baseInfo.value.SaleName)
  }
}

//定义数据
const state = reactive({
  formData: {},
  loading:false,
  options:[],
  rules: {
    ContractNum: [
      {required: true, message: '请输入合同编号', trigger: 'blur'},
      {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
    ],
    EntryName: [
      {required: true, message: '请输入项目名称', trigger: 'blur'},
      {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
    ]
   },

  table: {
    tableOptions: {
      widthMode: "auto",
      heightMode: "auto",
      defaultRowHeight: 40,
      rightFrozenColCount: 1,
    },
    busy:false,
    loadedData:[], // 已加载的数据
    border: true,
    rules: {
      CinvCode: [{ required: true, message: "请选择存货", trigger: "change" }],
      Unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
      Price: [{ required: true, message: "请输入单价", trigger: "blur" }],
      Quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
      Amount: [{ required: true, message: "请输入总价", trigger: "blur" }]
    },
    // firstColumn: { type: "index", label: "行号",props:'LineNum' }, // 显示序列号
    data: [],
    columns: [
      {
        key: "LineNum",
        dataKey: "LineNum",
        title: "行号",
        width: 60,
        fixed: "left",
      },
      {
        key: "CinvCode",
        dataKey: "CinvCode",
        title: "存货编码",
        width: "130",
      },
      {
        key: "CinvName",
        dataKey: "CinvName",
        title: "存货名称",
        width: "200",
      },
      {
        key: "Unit",
        dataKey: "Unit",
        title: "单位",
        width: "60",
      },
      {
        key: "CustCinvCode",
        dataKey: "CustCinvCode",
        title: "合同序号",
        width: "80",
      },
      {
        key: "CustCinvName",
        dataKey: "CustCinvName",
        title: "客户存货名称",
        width: "220",
      },
      {
        key: "CustCinvAdd",
        dataKey: "CustCinvAdd",
        title: "客户存货规格",
        width: "220",
      },
      {
        key: "JFDate",
        dataKey: "JFDate",
        title: "交付时间",
        width: "140",
      },
      {
        key: "Price",
        dataKey: "Price",
        title: "含税单价",
        width: "120",
      },
      {
        key: "Quantity",
        dataKey: "Quantity",
        title: "数量",
        width: "120",
      },
      {
        key: "Amount",
        dataKey: "Amount",
        title: "价税合计",
        width: "110",
      },
      {
        key: "Rate",
        dataKey: "Rate",
        title: "税率",
        width: "120",
      },
      {
        key: "Tax",
        dataKey: "Tax",
        title: "税额",
        width: "110",
      },
      {
        key: "iNatPrice",
        dataKey: "iNatPrice",
        title: "无税单价",
        width: "110",
      },
      {
        key: "iNatAmount",
        dataKey: "iNatAmount",
        title: "无税金额",
        width: "110",
      },

      {
        key: "TDYSFile",
        dataKey: "TDYSFile",
        title: "通电验收文件",
        width: "110",
      },
      {
        key: "FHTZDFile",
        dataKey: "FHTZDFile",
        title: "交货验收文件",
        width: "110",
      },
      {
        key: "JSDFile",
        dataKey: "JSDFile",
        title: "结算资料",
        width: "110",
      },
      {
        key: "YSaleQty",
        dataKey: "YSaleQty",
        title: "已下订单数量",
        width: "120",
      },
      {
        key: "YSaleAmount",
        dataKey: "YSaleAmount",
        title: "已下订单金额",
        width: "120",
      },
      {
        key: "YFHQty",
        dataKey: "YFHQty",
        title: "已发货数量",
        width: "100",
      },
      {
        key: "YFHAmount",
        dataKey: "YFHAmount",
        title: "已发货金额",
        width: "100",
      },
      {
        key: "YJSQty",
        dataKey: "YJSQty",
        title: "已结算数量",
        width: "100",
      },
      {
        key: "YJSAmount",
        dataKey: "YJSAmount",
        title: "已结算金额",
        width: "100",
      },
      {
        key: "YFHYSQty",
        dataKey: "YFHYSQty",
        title: "已发货验收数量",
        width: "140"
      },{
        key: "YTDYSQty",
        dataKey: "YTDYSQty",
        title: "已通电验收数量",
        width: "140"
      },
      {
        key: "Remark",
        dataKey: "Remark",
        title: "备注",
        width: "140",
      },
      {
        key: "RowState",
        dataKey: "RowState",
        title: "状态",
        width: 80,
        fixed:'right'
      },
      {
        key: "operatorT",
        dataKey: "operatorT",
        title: "操作",
        width: 60,
        fixed:'right'
      }
    ],

    exportConfig: [ // 导出Excel表格配置
      {
        title: '*序号',
        key: 'LineNum',
        type: 'text'
      },
      {
        title: '存货编码',
        key: 'CinvCode',
        type: 'text'
      },
        {
          title: '*产品名称',
          key: 'CinvName',
          type: 'text'
        },

        {
          title: '*单位',
          key: 'Unit',
          type: 'text'
        },
        {
          title: '*合同序号',
          key: 'CustCinvCode',
          type: 'text'
        },
        {
          title: '*合同名称',
          key: 'CustCinvName',
          type: 'text'
        },
        {
          title: '*合同型号',
          key: 'CustCinvAdd',
          type: 'text'
        },
        {
          title: '*单价',
          key: 'Price',
          type: 'text'
        },
        {
          title: '*数量',
          key: 'Quantity',
          type: 'text'
        },
        {
          title: '税率',
          key: 'Rate',
          type: 'text'
        },
        {
          title: '标记(新增不填)',
          key: 'Id',
          type: 'text'
        },
        {
          title: '交货日期',
          key: 'JFDate',
          type: 'date'
        },
      {
        title: '备注信息',
        key: 'Remark',
        type: 'text'
      },

      {
        title: '变更原因',
        key: 'BgRemark',
        type: 'text'
      },

    ],
  },
  // 下拉选择项
  listTypeInfo: [],
  tableZfBz: {
    rules: {
      TermContent: [{ required: true, message: "请选择支付条款", trigger: "blur" }],
      TermID: [{ required: true, message: "请选择支付条款", trigger: "blur" }]
    },
    // firstColumn: { type: "index", label: "序列" }, // 显示序列号
    data: [],
    columns: [
      {
        prop: "LineNum",
        label: "行号",
        placeholder: "请选择支付标准",
        minWidth: "60",
      },
      {
        prop: "Type",
        label: "支付类型",
        minWidth: "100",
        headerRequired: true,
        slotName: "ZfType",
        configEdit: {
          rules: { required: true, message: "请选择支付类型", trigger: "change" },
        }
      },
      // {
      //   prop: "TermID",
      //   label: "支付条件",
      //   placeholder: "请选择支付条件",
      //   width: "200",
      //   canEdit: true,
      //   headerRequired: true,
      //   configEdit: {
      //     label: "支付条件",
      //     type: "select-arr",
      //     editSlotName: "TermID",
      //     editComponent: "el-select",
      //   },
      // },
      {
        prop: "TermContent",
        label: "内容",
        minWidth: "500",
        noShowTip: true,
        allShow:true,
        showOverflowTooltip: false,
        canEdit: true,
        configEdit: {
          label: "支付条件",
          type: "input",
          editSlotName: "TermContent",
          editComponent: "el-input",
        },
      },
      {
        prop: "DataDay",
        label: "执行周期(天)",
        minWidth: "100",
        canEdit: true,
        headerRequired: true,
        configEdit: {
          label: "执行周期",
          rules: { required: true, message: "请输入天数", trigger: "blur" },
          type: "input",
          editComponent: "el-input",
        }
      },


      {
        prop: "Ratio",
        label: "比例",
        minWidth: "160",
        canEdit: true,
        placeholder: "请输入比例",
        bind: {
          disabled: true
        },
        headerRequired: true,
        configEdit: {
          label: "比例",
          append: "%",
          rules: { required: true, message: "请输入比例", trigger: "blur" },
          bind: { "prefix-icon": "el-icon-search" },
          editComponent: "el-input",
          editSlotName: "Ratio",
          // eventHandle: {
          //   change: ({ val, prop, scope }) => numSubChange(val, prop, scope)
          // }
        }
      },
      {
        prop: "Amount",
        label: "含税金额",
        minWidth: "180",
        canEdit: true,
        placeholder: "请输入金额",
        bind: {
          disabled: true
        },
        headerRequired: true,
        configEdit: {
          editSlotName: "Amount",
          label: "金额",
          rules: { required: true, message: "请输入比例", trigger: "blur" },
          bind: { "prefix-icon": "el-icon-search" },
          editComponent: "el-input",
          // eventHandle: {
          //   change: ({ val, prop, scope }) => numSubChange(val, prop, scope)
          // }
        }
      },
      {
        prop: "operator",
        label: "操作",
        minWidth: "180",
        fixed: "right",
        canEdit: true,
        placeholder: "操作",
        configEdit: {
          editSlotName: "operator",
        }
      },
    ],
  },
  userList:[],
  //存货下拉
  invList :[]
})


// 数量change事件
const numChange = (val, prop, index) => {
  let rate = (state.table.data[index].Rate /100) + 1
  state.table.data[index].Amount= (Number(state.table.data[index].Quantity || 0) * Number(state.table.data[index].Price || 0)).toFixed(2)//含税金额
  state.table.data[index].iNatPrice=(Number(state.table.data[index].Price || 0) / rate).toFixed(5)//不含税单价=含税单价 / 1.13

  state.table.data[index].Tax=( (state.table.data[index].Amount || 0) - ((state.table.data[index].Amount || 0) / rate)).toFixed(2)//税额
  state.table.data[index].iNatAmount=((state.table.data[index].Amount || 0 ) - state.table.data[index].Tax).toFixed(2)//不含税金额 = 含税金额 * 1.13

  //计算合同金额
  console.log(state.table.data,"1212")

  let reduce = state.table.data.reduce((acc, cur) => {
    return acc + (Number(cur.Amount) || 0);
  }, 0);
  console.log(reduce,"1212")

  baseInfo.value.ContractAmount =Number(reduce)

  state.tableZfBz.data.forEach(item=>{
    if (item.Ratio){
      item.Amount = (Number(reduce) * (Number(item.Ratio)/100)).toFixed(2)
    }
  })
}

// 数量change事件
// 数量change事件
const numSubChange = (val, prop, scope) => {
  let contractAmount = baseInfo.value.ContractAmount;
  if (contractAmount!==null && contractAmount!==undefined && contractAmount!=='' && state.tableZfBz.data.length>0){
    //计算比例及金额，输入金额计算比例，输入比例计算金额，需要考虑为空情况
    if (prop==='ContractAmount'){
      state.tableZfBz.data.forEach(item=>{
        if (item.Amount){
          item.Ratio = ((Number(item.Amount) / Number(contractAmount))*100).toFixed(2)
        }else {
          item.Amount = (Number(contractAmount) * (Number(item.Ratio)/100)).toFixed(2)
        }
      })
    }
    else if (prop==='Amount'){
      state.tableZfBz.data[scope.$index].Ratio = ((Number(val) / Number(contractAmount))*100).toFixed(2)
    }else{
      state.tableZfBz.data[scope.$index].Amount = (Number(contractAmount) * (Number(val)/100)).toFixed(2)
    }


  }
}



const cubasdoc = cubasdocStore()


//实时更新同步数据
// watch(() => props.subList, (newValue, oldValue) => {
//       state.table.data = newValue
//     }, { deep: true },

//)//实时更新同步数据
// watch(() => props.tremZF, (newValue, oldValue) => {

//       state.tableZfBz.data = newValue ? newValue : [];
//     }, { deep: true },
// )


onMounted(() => {
  state.table.data = subList.value?subList.value:[];
  // generateMockData(500,1)

  state.tableZfBz.data = tremZF.value?tremZF.value:[];

  getTermContent()
  getUserList()
  cusoptions.value = cubasdoc.data
})


//获取人员档案
const getUserList = async () => {
  let data = {
    page: 1,
    pagesize: 100000
  }
  let sqlString = {
    sqlString:
        'select cPsn_Name,cPsn_Num,cDept_num,cDepName from hr_hi_person p left join Department d on p.cDept_num = d.cDepCode'
  }

  let { Rows } = await findbaseBasicManage(data, sqlString)

  state.userList = Rows

}

//获取条款内容
const getTermContent = debounce(async (data) => {

  let {Data} =  await GetTK({Code: props.Id,Name:''});
  state.listTypeInfo = Data

},false,300)



//选择项
const cusoptions = ref([])
const cnvbasdocMethod = (query) => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = cubasdoc.data
  }
}

function  addTowTable () {
  let maxLineNum = 0;
  if (state.table.data.length > 0) {
    maxLineNum = Math.max(...state.tableZfBz.data.map(item => item.LineNum || 0));
  }
  state.tableZfBz.data?.push({
    //获取最大行号加1
    LineNum: maxLineNum + 1,
    TermID: null,
    TermContent: null,
    File1: null,
    File2: null,
    File3: null,
  })
}


const xTable = ref(null)
function handleExport(fileName='',idName = "#singleTab",xlsxParam={ raw: true }){
  const $table = xTable.value
  if ($table) {
    $table.exportData({
      type: 'xlsx'
    })
  }
}

async function handBdImport(file) {
  let res = await DetailImoprtExcel({file: file})
  if (res.Code ===  "Error") {
    ElMessage.error({
      message: res.Result,
      duration: 10000,
      showClose: true
    });
    return;
  }

  state.table.data=res.Data?.SubList
  emit('update:SubList', state.table.data)
}

function numChange2 (row) {
  let rate = (row.Rate /100) + 1
  row.Amount= (Number(row.Quantity || 0) * Number(row.Price || 0)).toFixed(2)//含税金额
  row.iNatPrice=(Number(row.Price || 0) / rate).toFixed(6)//不含税单价=含税单价 / 1.13
  row.Tax=( (row.Amount || 0) - ((row.Amount || 0) / rate)).toFixed(2)//税额
  row.iNatAmount=((row.Amount || 0 ) - row.Tax).toFixed(2)//不含税金额 = 含税金额 * 1.13
}



function  addOneTable () {
  let maxLineNum = 0;
  if (state.table.data.length > 0) {
    maxLineNum = Math.max(...state.table.data.map(item => item.LineNum || 0));
  }
  state.table.data.push({
    //获取最大行号加1
    LineNum: maxLineNum + 1,
    Amount: null,
    Quantity: null,
    Price: [],
    Unit: null,
    CinvName: null,
    CinvCode: null,
    Rate: props.baseInfo.Rate,
  })
}

//存货选择
function updateInv(e,row){

  //过滤客户
  let invoptions = state.invList.filter((its) => {
    return (its.cInvCode.toLowerCase().includes(e.toLowerCase()))
  })[0]
  if (invoptions){
    //赋值
    row.CinvName = invoptions.cInvName
    // row.Unit = invoptions.cComUnitCode
    row.Unit = invoptions.CComUnitName
  }

}
//支付条件选择
function updateZfTk(e,row){
  let zftk = state.listTypeInfo.filter((its) => {
    return (its.Id.toLowerCase().includes(e.toLowerCase()))
  })[0]
  if (zftk){
    //赋值
    row.TermContent = zftk.Content
    row.DataDay = zftk.Days
  }
}


//查询存货 -- 增加防抖函数
const remoteMethod = debounce(async (query) => {
  if (query) {
    state.loading = true
    state.loading = false

    let invData = {
      Code: query,
    }
    let {Data} = await GetInventory2(invData)
    state.invList = Data
    state.options = state.invList.filter((item) => {
      return (item.cInvName.toLowerCase().includes(query.toLowerCase()) || item.cInvCode.toLowerCase().includes(query.toLowerCase()))
    })
  } else {
    state.options = []
  }
},200,false)

// 获取文件名称
function getFileStatus(files) {
  // 判断list中FileAdd是否都有值，全部有值返回完整，部分返回部分上传
  if (!Array.isArray(files) || files.length === 0) {
    return '无文件';
  }

  const allHaveValues = files.every(file => file.FileAdd !== undefined && file.FileAdd !== null && file.FileAdd !== '');
  const someHaveValues = files.some(file => file.FileAdd !== undefined && file.FileAdd !== null && file.FileAdd !== '');

  if (allHaveValues) {
    return 'Y';
  } else if (someHaveValues) {
    return 'B';
  } else {
    return 'N';
  }
}






defineExpose({validateTable,formRef})

</script>

<style scoped lang="scss">

.el-form-item {
  --font-size: 12px;
  --el-form-label-font-size: var(--font-size);
  margin-bottom: 2px!important;
}

/* 隐藏未加载的行 */
:deep(.hidden-row) {
  display: none;
}

</style>

<style lang="scss">

.mytable-scrollbar {
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 4px;
  }
}


/** 默认模式 */
[data-vxe-ui-theme="light"] {
  .mytable-scrollbar {
    ::-webkit-scrollbar-track,
    ::-webkit-scrollbar-corner {
      background-color: #FFFFFF;
    }
    ::-webkit-scrollbar-thumb {
      background-color: #bfbfbf;
    }
    ::-webkit-scrollbar-thumb:hover,
    ::-webkit-scrollbar-thumb:active {
      background-color: #787878;
    }
  }
}

/** 暗黑模式 */
[data-vxe-ui-theme="dark"] {
  .mytable-scrollbar {
    ::-webkit-scrollbar-track,
    ::-webkit-scrollbar-corner {
      background-color: #151518;
    }
    ::-webkit-scrollbar-thumb {
      background-color: #bfbfbf;
    }
    ::-webkit-scrollbar-thumb:hover,
    ::-webkit-scrollbar-thumb:active {
      background-color: #A3A6AD;
    }
  }
}
</style>
